/**
 * 项目名称：拉钩项目
 * 文件名称：WindowUtils.java
 * 版本：1.0
 * CopyRight：2013 北京云顶畅游 版权所有
 */
package net.hvacapp.cmvrfforandroid.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Window窗口操作工具类
 *
 * @author hailong.han
 * @date 2013-6-7
 * @time 下午10:26:57
 */
public class WindowUtils {

    private final static String TAG = WindowUtils.class.getSimpleName();

    /**
     * 得到屏幕的宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getWidth();
    }

    /**
     * 得到屏幕的高度
     *
     * @param context
     * @return
     */
    @SuppressWarnings("deprecation")
    public static int getScreenHeight(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getHeight();
    }

    /**
     * 得到屏幕的密度
     *
     * @param context
     * @return
     */
    public static float getScreenDensity(Context context) {
        try {
            DisplayMetrics dm = new DisplayMetrics();
            WindowManager manager = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            manager.getDefaultDisplay().getMetrics(dm);
            return dm.density;
        } catch (Exception ex) {
            Log.e(TAG, ex.toString());
        }
        return 1.0f;
    }

    /**
     * 获取屏幕的密度
     *
     * @param context
     * @return
     */
    public static float getScreenDisplayMetrics(Context context) {
        try {
            DisplayMetrics dm = context.getResources().getDisplayMetrics();
            return dm.density;
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        return 1.0f;
    }

    /**
     * 判断程序是否是在前台显示
     *
     * @param context
     * @return
     */
    public static boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getApplicationContext().getSystemService(
                        Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();

        List<RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    /**
     * 需要&lt;uses-permission android:name="android.permission.GET_TASKS"/&gt;权限
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isTopPackage(Context context, String packageName) {
        ActivityManager manager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasksInfo = manager.getRunningTasks(1);
        if (tasksInfo.size() > 0) {
            // 应用程序位于堆栈的顶层
            if (packageName.equals(tasksInfo.get(0).topActivity
                    .getPackageName())) {
                return true;
            }
        }
        return false;
    }

    // /**
    // * 获取运行最顶部的activity
    // * @param context
    // * @return
    // */
    // public static Activity getTopActivity(Context context) {
    // ActivityManager manager =
    // (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
    // List<RunningTaskInfo> tasksInfo = manager.getRunningTasks(1);
    // if (tasksInfo.size() > 0) {
    // RunningTaskInfo taskInfo = tasksInfo.get(0);
    //
    // ComponentName cn = taskInfo.topActivity;
    //
    // if (cn != null) {
    // String activityName = cn.getClassName();
    // }
    // }
    // return null;
    // }

    /**
     * 检测某ActivityUpdate是否在当前Task的栈顶 需要&lt;uses-permission
     * android:name="android.permission.GET_TASKS"/&gt;权限
     */
    static public boolean isTopActivity(Context context, Class<?> clz) {
        return isTopActivity(context, clz.getName());
    }

    /**
     * 需要&lt;uses-permission android:name="android.permission.GET_TASKS"/&gt;权限
     *
     * @param context
     * @param className
     * @return
     */
    public static boolean isTopActivity(Context context, String className) {
        ActivityManager manager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
        String cmpNameTemp = null;
        if (null != runningTaskInfos) {
            cmpNameTemp = runningTaskInfos.get(0).topActivity.getClassName();
            Log.e("cmpname", "cmpname:" + className);
        }
        if (null == cmpNameTemp)
            return false;
        return cmpNameTemp.equals(className);
    }

    /**
     * 需要&lt;uses-permission android:name="android.permission.GET_TASKS"/&gt;权限
     *
     * @param context
     * @return
     */
    static public boolean isLauncherRunnig(Context context) {
        boolean result = false;
        List<String> names = getAllTheLauncher(context);
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appList = mActivityManager
                .getRunningAppProcesses();
        for (RunningAppProcessInfo running : appList) {
            if (running.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (int i = 0; i < names.size(); i++) {
                    if (names.get(i).equals(running.processName)) {
                        result = true;
                        break;
                    }
                }
            }
        }
        return result;
    }

    /**
     * 需要&lt;uses-permission android:name="android.permission.GET_TASKS"/&gt;权限
     *
     * @param context
     * @return
     */
    static private List<String> getAllTheLauncher(Context context) {
        List<String> names = null;
        PackageManager pkgMgt = context.getPackageManager();
        Intent it = new Intent(Intent.ACTION_MAIN);
        it.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> ra = pkgMgt.queryIntentActivities(it, 0);
        if (ra.size() != 0) {
            names = new ArrayList<String>();
        }
        for (int i = 0; i < ra.size(); i++) {
            String packageName = ra.get(i).activityInfo.packageName;
            names.add(packageName);
        }
        return names;
    }

    // 判断某个服务是否运行
    public static boolean isServiceRunning(Context context, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningServiceInfo> runningServiceList = activityManager
                .getRunningServices(30);

        for (int i = 0; i < runningServiceList.size(); i++) {
            if (runningServiceList.get(i).service.getClassName().equals(
                    className)) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int dpToPx(Resources res, int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                res.getDisplayMetrics());
    }

    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 是否在窗口外面
     *
     * @param context
     * @param event
     * @return
     */
    public static boolean isOutOfBounds(Activity context, MotionEvent event) {
        final int x = (int) event.getX();
        final int y = (int) event.getY();
        final int slop = ViewConfiguration.get(context)
                .getScaledWindowTouchSlop();
        final View decorView = context.getWindow().getDecorView();
        return (x < -slop) || (y < -slop)
                || (x > (decorView.getWidth() + slop))
                || (y > (decorView.getHeight() + slop));
    }
}
